import { reactive } from 'vue';

import FieldTable from './FieldTable.vue';
import ButtonTableCom from './ButtonConfig.vue';

import { useDebounceFn } from '@vueuse/core';
import { FormSchema } from '/@/components/Table';
import { DICT } from '/@/enums/dict';
import { getDictTypeListApi } from '/@/api/admin/dict';
import { getDBTableNamesApi, getModelAllFormApi } from '/@/api/config-center/model-design';
import { CLIENT_TYPE_ENUM } from '/@/views/config-center/design-form-list/components/form-design/typings/form-type';

export interface SubTableInstance {
  setValues: (data: Indexable) => void;
  getValues: PromiseFn<Indexable>;
}
const tableCodeParams = reactive({ tableCode: '', dataSource: '' });
const formModuleParam = reactive({ modelName: '' });

export enum OperationType {
  DIALOG = 'dialog',
  BATCH = 'batch',
}

const columnValid = (_, value) => {
  if (!value.length) {
    return Promise.reject();
  }
  const idx = value.findIndex((el) => !el.label || !el.field);
  if (idx > -1) {
    const emptyItem = value[idx];
    const prefix = `第${idx + 1}行`;
    if (!emptyItem.label) {
      return Promise.reject(prefix + '字段名称未输入');
    }
    if (!emptyItem.field) {
      return Promise.reject(prefix + '字段编码未输入');
    }
  }

  return Promise.resolve();
};
const btnValid = (_, value) => {
  if (!value.length) {
    return Promise.reject();
  }
  const idx = value.findIndex((el) => !el.label || !el.eventType);
  if (idx > -1) {
    const emptyItem = value[idx];
    const prefix = `第${idx + 1}行`;
    if (!emptyItem.label) {
      return Promise.reject(prefix + '字段名称未输入');
    }
    if (!emptyItem.eventType) {
      return Promise.reject(prefix + '事件类型未输入');
    }
  }

  return Promise.resolve();
};
export const formItemSchema = (sourceType: string, client = CLIENT_TYPE_ENUM.PC): FormSchema[] => {
  tableCodeParams.dataSource = sourceType;
  const operationTypeList = [
    {
      label: '弹出式',
      value: 'dialog',
    },
    {
      label: '平铺式',
      value: 'batch',
    },
  ];
  if (client === CLIENT_TYPE_ENUM.APP) {
    operationTypeList.push({
      label: '卡片式',
      value: 'card',
    });
  }

  return [
    {
      required: true,
      field: 'modelId',
      label: '绑定模型',
      component: 'ApiSelect',
      componentProps() {
        return {
          showSearch: true,
          filterOption: false,
          api: getModelAllFormApi,
          labelField: 'modelName',
          valueField: 'modelId',
          params: formModuleParam,
          onSearch: useDebounceFn((v) => {
            formModuleParam.modelName = v;
          }, 200),
          getPopupContainer: () => document.body,
        };
      },
      // ifShow: () => classify === MODEL_TYPE.LIST,
    },
    {
      field: 'childTableCode',
      label: '子表名',
      required: true,
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: getDBTableNamesApi,
          showSearch: true,
          filterOption: false,
          labelField: 'name',
          valueField: 'name',
          resultField: 'records',
          placeholder: '请选择子表名',
          params: tableCodeParams,
          onSearch: useDebounceFn((v) => {
            tableCodeParams.tableCode = v;
          }, 200),
          getPopupContainer: () => document.body,
        };
      },
    },

    {
      field: 'childPrimaryCode',
      label: '子表主键',
      required: true,
      component: 'Input',
    },

    {
      field: 'primaryType',
      label: '主键类型',
      component: 'ApiSelect',
      required: true,
      defaultValue: 1,
      componentProps: {
        api: getDictTypeListApi,
        labelField: 'label',
        valueField: 'intValue',
        params: {
          type: DICT.CHILD_TABLE_PRIMARY_TYPE,
        },
        getPopupContainer: () => document.body,
      },
    },
    {
      field: 'childForeignCode',
      label: '子表外键',
      component: 'Input',
    },

    {
      field: 'operationType',
      label: '操作类型',
      required: false,
      defaultValue: OperationType.BATCH,
      component: 'Select',
      componentProps: {
        options: operationTypeList,
      },
    },
    {
      field: 'dialogWidth',
      label: '弹框宽度',
      required: false,
      component: 'Input',
      ifShow: ({ values }) => values.operationType === OperationType.DIALOG,
    },
    {
      field: 'width',
      label: '字段宽度',
      required: false,
      component: 'Input',
    },
    {
      field: 'pageSize',
      label: '分页行数',
      required: false,
      defaultValue: 0,
      component: 'InputNumber',
    },
    {
      field: 'tableColumn',
      label: '字段定义',
      required: true,
      component: 'Input',
      itemProps: {
        autoLink: false,
      },
      rules: [{ validator: columnValid, trigger: 'change' }],
      ifShow: ({ values }) => sourceType && values.childTableCode,
      render({ model, field, values }) {
        return (
          <FieldTable
            dataSource={sourceType}
            tableCode={values.childTableCode}
            vModel={[model[field], 'data']}
          />
        );
      },
      colProps: { span: 22, lg: 22 },
    },
    {
      field: 'tableBtn',
      label: '操作定义',
      required: true,
      component: 'Input',
      itemProps: {
        autoLink: false,
      },
      rules: [{ validator: btnValid, trigger: 'change' }],

      render({ model, field }) {
        return <ButtonTableCom vModel={[model[field], 'data']} />;
      },
      colProps: { span: 22, lg: 22 },
    },
    {
      field: 'windowParams',
      label: '窗口参数',
      required: false,
      component: 'InputTextArea',
      componentProps: {
        rows: 4,
      },
      colProps: { span: 22, lg: 22 },
    },
    {
      field: 'limitCondition',
      label: '限制条件',
      required: false,
      component: 'InputTextArea',
      componentProps: {
        rows: 4,
      },
      colProps: { span: 22, lg: 22 },
    },
  ];
};
